package com.soft.base.util;

import com.soft.base.exception.BizException;
import com.xiaoleilu.hutool.lang.Snowflake;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
/**
 * class
 *
 * @author user
 * @date 2020/06/05
 */
public class IDUtil {
    public static long getMachineWorkId() {
        try {
            String ip = InetAddress.getLocalHost().getHostAddress();
            InetAddress i = InetAddress.getByName(ip);
            return ByteBuffer.wrap(i.getAddress()).getInt() & 0x0FFFFFFFFL;
        } catch (UnknownHostException e) {
            BizException.throwException(e.getMessage());
        }
        return 0L;
    }

    private static Snowflake snowflake;

    static {
        long machineId = getMachineWorkId();
        long workerId = (machineId & 0x1F);
        long datacenterId = (machineId & (0x1F << 5)) >> 5;
        snowflake = new Snowflake(workerId, datacenterId);
    }

    public static long nextId() {
        return snowflake.nextId();
    }

}
